<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="追溯类型" prop="traceType">
        <el-select v-model="queryParams.traceType" placeholder="请选择追溯类型" clearable>
          <el-option label="正向追溯" value="forward" />
          <el-option label="反向追溯" value="reverse" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次号" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单ID" prop="workOrderId">
        <el-input
          v-model="queryParams.workOrderId"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleTrace"
          v-hasPermi="['mes:traceability:query']"
        >开始追溯</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:traceability:export']"
        >导出报告</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 追溯结果展示 -->
    <el-card v-if="traceResult" class="box-card">
      <div slot="header" class="clearfix">
        <span>追溯结果</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="clearResult">清除</el-button>
      </div>
      
      <!-- 追溯记录表格 -->
      <el-table v-loading="loading" :data="traceResult.records" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="追溯编码" align="center" prop="traceCode" />
        <el-table-column label="追溯类型" align="center" prop="traceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_trace_type" :value="scope.row.traceType"/>
          </template>
        </el-table-column>
        <el-table-column label="对象类型" align="center" prop="objectType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_object_type" :value="scope.row.objectType"/>
          </template>
        </el-table-column>
        <el-table-column label="工单编号" align="center" prop="workOrderCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="追溯状态" align="center" prop="traceStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_trace_status" :value="scope.row.traceStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewTree(scope.row)"
              v-hasPermi="['mes:traceability:query']"
            >查看追溯链</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 追溯树对话框 -->
    <el-dialog title="追溯链" :visible.sync="treeOpen" width="80%" append-to-body>
      <div id="traceTree" style="height: 500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import { forwardTrace, reverseTrace, getTraceByWorkOrder, getTraceTree, generateReport } from "@/api/mes/traceability/traceability"

export default {
  name: "TraceQuery",
  dicts: ['mes_trace_type', 'mes_object_type', 'mes_trace_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        traceType: null,
        batchCode: null,
        productId: null,
        workOrderId: null
      },
      // 追溯结果
      traceResult: null,
      // 追溯树对话框
      treeOpen: false
    };
  },
  created() {
    // 初始化时不加载数据
    this.loading = false;
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.handleTrace();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.traceResult = null;
    },
    /** 开始追溯 */
    handleTrace() {
      this.loading = true;
      
      if (this.queryParams.batchCode) {
        // 正向追溯
        forwardTrace(this.queryParams.batchCode).then(response => {
          this.traceResult = response.data;
          this.loading = false;
        });
      } else if (this.queryParams.productId) {
        // 反向追溯
        reverseTrace(this.queryParams.productId).then(response => {
          this.traceResult = response.data;
          this.loading = false;
        });
      } else if (this.queryParams.workOrderId) {
        // 工单追溯
        getTraceByWorkOrder(this.queryParams.workOrderId).then(response => {
          this.traceResult = response.data;
          this.loading = false;
        });
      } else {
        this.$modal.msgError("请输入批次号、产品ID或工单ID进行追溯");
        this.loading = false;
      }
    },
    /** 清除结果 */
    clearResult() {
      this.traceResult = null;
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.traceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看追溯树 */
    handleViewTree(row) {
      this.treeOpen = true;
      this.$nextTick(() => {
        getTraceTree(row.traceId).then(response => {
          // 这里可以使用图表库如echarts来渲染追溯树
          console.log('追溯树数据:', response.data);
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      if (!this.traceResult || !this.traceResult.records.length) {
        this.$modal.msgError("请先进行追溯查询");
        return;
      }
      
      const params = {
        traceType: this.queryParams.traceType || 'batch',
        objectId: this.queryParams.batchCode || this.queryParams.productId || this.queryParams.workOrderId
      };
      
      generateReport(params).then(response => {
        this.$modal.msgSuccess("报告生成成功");
        console.log('追溯报告:', response.data);
      });
    }
  }
};
</script>